'use client'

import { useState, useEffect } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { Input } from '@/components/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { 
  Plus, 
  Search, 
  Filter, 
  MoreHorizontal,
  Edit,
  Trash2,
  Package,
  DollarSign,
  FileText,
  Users,
  Calendar,
  AlertTriangle,
  CheckCircle,
  Clock
} from 'lucide-react'

interface BOMItem {
  id: string
  partNumber: string
  name: string
  description?: string
  category: string
  quantity: number
  unit: string
  unitCost?: number
  totalPrice?: number
  supplier?: {
    id: string
    name: string
    code: string
  }
  manufacturer?: string
  partNumberAlt?: string
  datasheet?: string
  lifecycle: string
  leadTime?: number
  moq?: number
  mpq?: number
  location?: string
  notes?: string
}

interface BOM {
  id: string
  version: string
  name: string
  description?: string
  status: string
  totalCost?: number
  currency: string
  createdAt: string
  project: {
    id: string
    name: string
    key: string
  }
  creator: {
    id: string
    name: string
    username: string
  }
  items: BOMItem[]
  _count: {
    items: number
    hardwareVersions: number
    requirements: number
  }
}

export function BOMsList() {
  const [boms, setBOMs] = useState<BOM[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState('')
  const [statusFilter, setStatusFilter] = useState('all')
  const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false)
  const [selectedBOM, setSelectedBOM] = useState<BOM | null>(null)
  const [isBOMItemsDialogOpen, setIsBOMItemsDialogOpen] = useState(false)
  const [newBOM, setNewBOM] = useState({
    version: '',
    name: '',
    description: '',
    status: 'DRAFT'
  })

  useEffect(() => {
    fetchBOMs()
  }, [])

  const fetchBOMs = async () => {
    try {
      const response = await fetch('/api/boms')
      if (response.ok) {
        const data = await response.json()
        setBOMs(data)
      }
    } catch (error) {
      console.error('Error fetching BOMs:', error)
    } finally {
      setLoading(false)
    }
  }

  const createBOM = async () => {
    try {
      // Get the first project and user from the database
      const projectsResponse = await fetch('/api/projects')
      const projectsData = await projectsResponse.json()
      
      const usersResponse = await fetch('/api/users')
      const usersData = await usersResponse.json()
      
      if (projectsData.length === 0) {
        alert('请先创建项目')
        return
      }
      
      if (usersData.length === 0) {
        alert('请先创建用户')
        return
      }
      
      // Use the first project and user as defaults
      const projectId = projectsData[0].id
      const creatorId = usersData[0].id
      
      const response = await fetch('/api/boms', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...newBOM,
          projectId,
          creatorId
        })
      })

      if (response.ok) {
        setIsCreateDialogOpen(false)
        setNewBOM({
          version: '',
          name: '',
          description: '',
          status: 'DRAFT'
        })
        fetchBOMs()
      } else {
        const errorData = await response.json()
        console.error('Error creating BOM:', errorData.error)
        alert(`创建BOM失败: ${errorData.error}`)
      }
    } catch (error) {
      console.error('Error creating BOM:', error)
      alert('创建BOM失败，请重试')
    }
  }

  const filteredBOMs = boms.filter(bom => {
    const matchesSearch = bom.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         bom.version.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         bom.description?.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesStatus = statusFilter === 'all' || bom.status === statusFilter
    return matchesSearch && matchesStatus
  })

  const getStatusColor = (status: string) => {
    const colors: Record<string, string> = {
      DRAFT: 'bg-gray-100 text-gray-800',
      REVIEW: 'bg-yellow-100 text-yellow-800',
      APPROVED: 'bg-blue-100 text-blue-800',
      PRODUCTION: 'bg-green-100 text-green-800',
      ARCHIVED: 'bg-red-100 text-red-800'
    }
    return colors[status] || 'bg-gray-100 text-gray-800'
  }

  const getLifecycleColor = (lifecycle: string) => {
    const colors: Record<string, string> = {
      ACTIVE: 'bg-green-100 text-green-800',
      END_OF_LIFE: 'bg-red-100 text-red-800',
      OBSOLETE: 'bg-gray-100 text-gray-800',
      NEW: 'bg-blue-100 text-blue-800'
    }
    return colors[lifecycle] || 'bg-gray-100 text-gray-800'
  }

  if (loading) {
    return <div className="flex items-center justify-center h-64">加载中...</div>
  }

  return (
    <div className="space-y-6">
      {/* 页面标题和操作 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">BOM物料管理</h1>
          <p className="text-gray-600">管理产品物料清单和供应链信息</p>
        </div>
        <Dialog open={isCreateDialogOpen} onOpenChange={setIsCreateDialogOpen}>
          <DialogTrigger asChild>
            <Button>
              <Plus className="h-4 w-4 mr-2" />
              创建BOM
            </Button>
          </DialogTrigger>
          <DialogContent className="sm:max-w-[525px]">
            <DialogHeader>
              <DialogTitle>创建新BOM</DialogTitle>
              <DialogDescription>
                创建一个新的物料清单
              </DialogDescription>
            </DialogHeader>
            <div className="grid gap-4 py-4">
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="version" className="text-right">
                  版本
                </Label>
                <Input
                  id="version"
                  placeholder="V1.0"
                  value={newBOM.version}
                  onChange={(e) => setNewBOM(prev => ({ ...prev, version: e.target.value }))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="name" className="text-right">
                  名称
                </Label>
                <Input
                  id="name"
                  value={newBOM.name}
                  onChange={(e) => setNewBOM(prev => ({ ...prev, name: e.target.value }))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="description" className="text-right">
                  描述
                </Label>
                <Textarea
                  id="description"
                  value={newBOM.description}
                  onChange={(e) => setNewBOM(prev => ({ ...prev, description: e.target.value }))}
                  className="col-span-3"
                />
              </div>
              <div className="grid grid-cols-4 items-center gap-4">
                <Label htmlFor="status" className="text-right">
                  状态
                </Label>
                <Select
                  value={newBOM.status}
                  onValueChange={(value) => setNewBOM(prev => ({ ...prev, status: value }))}
                >
                  <SelectTrigger className="col-span-3">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="DRAFT">草稿</SelectItem>
                    <SelectItem value="REVIEW">审核中</SelectItem>
                    <SelectItem value="APPROVED">已批准</SelectItem>
                    <SelectItem value="PRODUCTION">生产中</SelectItem>
                    <SelectItem value="ARCHIVED">已归档</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </div>
            <DialogFooter>
              <Button onClick={createBOM}>创建BOM</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      {/* 搜索和筛选 */}
      <Card>
        <CardContent className="pt-6">
          <div className="flex items-center space-x-4">
            <div className="flex-1">
              <div className="relative">
                <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
                <Input
                  placeholder="搜索BOM..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                  className="pl-10"
                />
              </div>
            </div>
            <Select value={statusFilter} onValueChange={setStatusFilter}>
              <SelectTrigger className="w-32">
                <Filter className="h-4 w-4 mr-2" />
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部状态</SelectItem>
                <SelectItem value="DRAFT">草稿</SelectItem>
                <SelectItem value="REVIEW">审核中</SelectItem>
                <SelectItem value="APPROVED">已批准</SelectItem>
                <SelectItem value="PRODUCTION">生产中</SelectItem>
                <SelectItem value="ARCHIVED">已归档</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </CardContent>
      </Card>

      {/* BOM列表 */}
      <div className="grid gap-6">
        {filteredBOMs.map((bom) => (
          <Card key={bom.id} className="hover:shadow-md transition-shadow">
            <CardHeader>
              <div className="flex items-start justify-between">
                <div className="space-y-2">
                  <div className="flex items-center space-x-2">
                    <Badge className={getStatusColor(bom.status)}>
                      {bom.status}
                    </Badge>
                    <Badge variant="outline" className="text-xs">
                      {bom.version}
                    </Badge>
                  </div>
                  <CardTitle className="text-lg">{bom.name}</CardTitle>
                  <CardDescription className="line-clamp-2">
                    {bom.description || '暂无描述'}
                  </CardDescription>
                </div>
                <div className="flex items-center space-x-2">
                  <Button 
                    variant="outline" 
                    size="sm"
                    onClick={() => {
                      setSelectedBOM(bom)
                      setIsBOMItemsDialogOpen(true)
                    }}
                  >
                    <Package className="h-4 w-4 mr-2" />
                    查看物料
                  </Button>
                  <Button variant="ghost" size="icon">
                    <MoreHorizontal className="h-4 w-4" />
                  </Button>
                </div>
              </div>
            </CardHeader>
            <CardContent>
              <div className="space-y-4">
                {/* 项目信息 */}
                <div className="flex items-center space-x-2 text-sm text-gray-500">
                  <FileText className="h-4 w-4" />
                  <span>{bom.project.key} - {bom.project.name}</span>
                </div>

                {/* 统计信息 */}
                <div className="grid grid-cols-3 gap-4 text-sm">
                  <div className="flex items-center space-x-2">
                    <Package className="h-4 w-4 text-blue-600" />
                    <div>
                      <div className="font-medium">{bom._count.items}</div>
                      <div className="text-gray-500">物料项</div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <CheckCircle className="h-4 w-4 text-green-600" />
                    <div>
                      <div className="font-medium">{bom._count.hardwareVersions}</div>
                      <div className="text-gray-500">硬件版本</div>
                    </div>
                  </div>
                  <div className="flex items-center space-x-2">
                    <Clock className="h-4 w-4 text-purple-600" />
                    <div>
                      <div className="font-medium">{bom._count.requirements}</div>
                      <div className="text-gray-500">关联需求</div>
                    </div>
                  </div>
                </div>

                {/* 成本信息 */}
                {bom.totalCost && (
                  <div className="flex items-center space-x-2 text-sm">
                    <DollarSign className="h-4 w-4 text-green-600" />
                    <span>总成本: {bom.currency} {bom.totalCost.toLocaleString()}</span>
                  </div>
                )}

                {/* 创建信息 */}
                <div className="flex items-center justify-between text-xs text-gray-500">
                  <div className="flex items-center space-x-1">
                    <Users className="h-3 w-3" />
                    <span>{bom.creator.name}</span>
                  </div>
                  <div className="flex items-center space-x-1">
                    <Calendar className="h-3 w-3" />
                    <span>{new Date(bom.createdAt).toLocaleDateString()}</span>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredBOMs.length === 0 && (
        <Card>
          <CardContent className="pt-6">
            <div className="text-center py-12">
              <h3 className="text-lg font-medium text-gray-900 mb-2">暂无BOM</h3>
              <p className="text-gray-500 mb-4">创建您的第一个BOM来开始管理物料清单</p>
              <Button onClick={() => setIsCreateDialogOpen(true)}>
                <Plus className="h-4 w-4 mr-2" />
                创建BOM
              </Button>
            </div>
          </CardContent>
        </Card>
      )}

      {/* BOM物料项对话框 */}
      <Dialog open={isBOMItemsDialogOpen} onOpenChange={setIsBOMItemsDialogOpen}>
        <DialogContent className="sm:max-w-[800px]">
          <DialogHeader>
            <DialogTitle>{selectedBOM?.name} - 物料清单</DialogTitle>
            <DialogDescription>
              版本: {selectedBOM?.version} | 状态: {selectedBOM?.status}
            </DialogDescription>
          </DialogHeader>
          <div className="max-h-96 overflow-y-auto">
            {selectedBOM && selectedBOM.items.length > 0 ? (
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>物料编号</TableHead>
                    <TableHead>名称</TableHead>
                    <TableHead>分类</TableHead>
                    <TableHead>用量</TableHead>
                    <TableHead>单价</TableHead>
                    <TableHead>总价</TableHead>
                    <TableHead>供应商</TableHead>
                    <TableHead>状态</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {selectedBOM.items.map((item) => (
                    <TableRow key={item.id}>
                      <TableCell className="font-medium">{item.partNumber}</TableCell>
                      <TableCell>{item.name}</TableCell>
                      <TableCell>{item.category}</TableCell>
                      <TableCell>{item.quantity} {item.unit}</TableCell>
                      <TableCell>
                        {item.unitCost ? `${selectedBOM.currency} ${item.unitCost}` : '-'}
                      </TableCell>
                      <TableCell>
                        {item.totalPrice ? `${selectedBOM.currency} ${item.totalPrice}` : '-'}
                      </TableCell>
                      <TableCell>{item.supplier?.name || '-'}</TableCell>
                      <TableCell>
                        <Badge className={getLifecycleColor(item.lifecycle)}>
                          {item.lifecycle}
                        </Badge>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            ) : (
              <div className="text-center py-8">
                <Package className="h-12 w-12 text-gray-400 mx-auto mb-4" />
                <p className="text-gray-500">暂无物料项</p>
              </div>
            )}
          </div>
          <DialogFooter>
            <Button onClick={() => setIsBOMItemsDialogOpen(false)}>
              关闭
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}